package com.fzrskj.cloud.free.core.tool;

import ms.core.tool.StrTool;

import java.security.SecureRandom;

/**
 * CStrTool.
 *
 * @author zj.
 *         Created on 2018/8/31 0031.
 */
public class CStrTool extends StrTool {
    /**
     * convert string to double
     * @param v
     * @param defaultValue
     * @return
     */
    public static double strToDoubleDef(String v, float defaultValue){
        try{
            if (isBlankStr(v)) {
                return defaultValue;
            }

            return Double.parseDouble(v.trim());
        }catch (NumberFormatException e){
            e.printStackTrace();
            return defaultValue;
        }
    }

    /**
     * 随机数字子母.
     * @param length 长度.
     * @return
     */
    public static String randStr(Integer length) {
        char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
                'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
        return randCore(length, codeSequence);
    }

    /**
     * 随机字母.
     * @param length 长度.
     * @return String.
     */
    public static String randEnChar(Integer length) {
        char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
                'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
        return randCore(length, codeSequence);
    }

    /**
     * 随机数字.
     * @param length 长度.
     * @return
     */
    public static String randNum(Integer length) {
        char[] codeSequence = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
        return randCore(length, codeSequence);
    }

    /**
     * 随机符号.
     * @param length
     * @return
     */
    public static String randSymbol(Integer length) {
        // ()`~!@#$%^&*_-+=|{}[]:;'<>,.?
        char[] codeSequence = { '+', '-', '+', ')', '(', '*', '~', '!', '@', '#', '$', '%', '^', '&' };
        return randCore(length, codeSequence);
    }

    /**
     * 随机字符串生成.
     * @param length 长度.
     * @param codeSequence 取值范围.
     * @return String.
     */
    public static String randCore(Integer length, char[] codeSequence) {
        // 创建一个随机数生成器类
        SecureRandom random = new SecureRandom();
        StringBuffer randomCode = new StringBuffer();
        // 随机产生codeCount
        for (int i = 0; i < length; i++) {
            String code = String.valueOf(codeSequence[random.nextInt(10)]);
            // 将产生的四个随机数组合在一起。
            randomCode.append(code);
        }
        return randomCode.toString().toLowerCase();
    }
}
